package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.RedisNewsConst;
import com.dongdongshop.mapper.TbContentMapper;
import com.dongdongshop.pojo.TbContent;
import com.dongdongshop.pojo.TbContentExample;
import com.dongdongshop.service.TbContentServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Stream;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbContentServiceImpl implements TbContentServiceI {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private TbContentMapper tbContentMapper;

    @Override
    public List<TbContent> getFindAll() {
        return tbContentMapper.selectByExample(new TbContentExample());
    }

    @Override
    public TbContent getFidById(Long id) {
        return tbContentMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void addTbContent(TbContent tbContent) {
        tbContentMapper.insertSelective(tbContent);
    }

    @Override
    @Transactional
    public void updateTbContent(TbContent tbContent) {
        tbContentMapper.updateByPrimaryKeySelective(tbContent);
    }

    @Override
    public void deleteTbContent(List<Integer> list) {
        Stream<Integer> stream = list.stream();
        Consumer<Integer> consumer = id -> tbContentMapper.deleteByPrimaryKey(id.longValue());
        stream.forEach(consumer);
    }

    @Override
    public List<TbContent> getContentInfo(Long categoryId) {
        //用hash类型将图片存入Redis
        //先查询Redis中是否有值，如果有，直接返回。如果没有则查询数据库，然后再把数据保存到Redis中，最后返回
        String key = "contents";
        String fileId ="imgs:" +categoryId;
        if(redisTemplate.boundHashOps(key).hasKey(fileId)){
            List<TbContent> contentList = (List<TbContent>)redisTemplate.boundHashOps(key).get(fileId);
            return contentList;
        }else {
            List<TbContent> contents = tbContentMapper.getContentInfo(categoryId);
            redisTemplate.boundHashOps(key).put(fileId,contents);
            redisTemplate.boundHashOps(key).expire(1, TimeUnit.MINUTES);
            return contents;
        }
    }

}
